package com.yunchao.library.socket.utils

import java.nio.ByteBuffer
import java.nio.ByteOrder
import java.util.concurrent.ConcurrentLinkedQueue

object BufferPool {
    private val pool = ConcurrentLinkedQueue<ByteBuffer>()

    fun acquire(size: Int): ByteBuffer {
        return (pool.poll()?.takeIf { it.capacity() >= size }?.clear()
            ?: ByteBuffer.allocate(size).order(ByteOrder.BIG_ENDIAN)) as ByteBuffer
    }

    fun release(buffer: ByteBuffer) {
        pool.offer(buffer)
    }

    inline fun <T> use(size: Int, block: (ByteBuffer) -> T): T {
        val buffer = acquire(size)
        try {
            return block(buffer)
        } finally {
            release(buffer)
        }
    }
}
